package com.wss.module.user.ui.account.mvp.model;


import com.wss.common.base.mvp.BaseModel;
import com.wss.common.bean.User;
import com.wss.common.net.Api;
import com.wss.common.net.NetworkManage;
import com.wss.common.net.request.RequestParam;
import com.wss.common.utils.JsonUtils;
import com.wss.module.user.ui.account.mvp.contract.LoginContract;

import com.zhouyou.http.callback.CallBack;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;
import io.reactivex.Observable;
import ohos.aafwk.ability.ILifecycle;
import ohos.aafwk.ability.Lifecycle;
import ohos.aafwk.ability.LifecycleObserver;

import javax.security.auth.callback.Callback;

/**
 * Describe：登录Module
 * Created by 吴天强 on 2018/11/13.
 */
public class LoginModel extends BaseModel implements LoginContract.Model {

    public LoginModel(Lifecycle lifecycleOwner) {
        super(lifecycleOwner);
    }

    @Override
    public void login(String userName, String password, SimpleCallBack<User> callBack) {

        HttpParams params = new HttpParams();
        params.put("username", userName);
        params.put("password", password);
        NetworkManage.createPostForm().request(Api.LOGIN, params, new CallBack<String>() {

            @Override
            public void onStart() {
                callBack.onStart();
            }

            @Override
            public void onCompleted() {
                callBack.onCompleted();
            }

            @Override
            public void onError(ApiException e) {
                callBack.onError(e);
            }

            @Override
            public void onSuccess(String s) {
                System.out.println("==== result : " + s);
                int errorCode = JsonUtils.getInt(s, "errorCode");
                if (errorCode == 0) {
                    User user = JsonUtils.getObject(JsonUtils.getString(s, "data"), User.class);
                    callBack.onSuccess(user);
                } else {
                    String errorMsg = JsonUtils.getString(s, "errorMsg");
                    callBack.onError(new ApiException(new Throwable(errorMsg), errorCode));

                }
            }
        });
    }
}
